package com.doris.media.picker.result.contract

import android.content.Context
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContract
import com.doris.media.picker.activity.MediaPickerActivity
import com.doris.media.picker.model.MediaModel
import com.doris.media.picker.model.MediaPickerConfig
import com.doris.media.picker.model.MediaPickerParameter
import com.doris.media.picker.result.MediaPickerResult

class MediaPickerContract : ActivityResultContract<MediaPickerParameter, MediaPickerResult>() {

    private var mRequestCode = MediaPickerConfig.MEDIA_PICKER_DEFAULT_REQUEST_CODE

    override fun createIntent(context: Context, input: MediaPickerParameter?): Intent {
        val intent = Intent(context, MediaPickerActivity::class.java)
        if (input != null) {
            mRequestCode = input.requestCode
            intent.putExtra(MediaPickerConfig.MEDIA_PICKER, input)
            intent.putExtra(MediaPickerConfig.MEDIA_PICKER_DATA, input.pickerData)
            intent.putExtra(MediaPickerConfig.MEDIA_PICKER_MIME_TYPE, input.mimeTyp)
        }
        return intent
    }

    override fun parseResult(resultCode: Int, intent: Intent?): MediaPickerResult {
        val result = MediaPickerResult(mRequestCode)
        if (resultCode == MediaPickerConfig.MEDIA_PICKER_RESULT_OK && intent != null) {
            val pickerData = intent.getParcelableArrayListExtra<MediaModel>(
                MediaPickerConfig.MEDIA_PICKER_DATA
            )
            if (!pickerData.isNullOrEmpty()){
                result.addData(pickerData)
            }
        }
        return result
    }
}